package com.qfly.main.authentication.handler;

import com.qfly.main.common.bean.ErrorCode;
import com.qfly.main.common.enums.ErrorCodeEnum;
import com.qfly.main.common.utils.ResultUtil;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Wisdytech.cn
 * com.qfly.main.authentication.handler.qflyAuthenticationFailureHandler
 *
 * @author hailin.zhl
 * @date 2018/12/04
 */
@Component
public class QflyAuthenticationFailureHandler implements AuthenticationFailureHandler {


    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        ErrorCode errorCode = ErrorCode.builder()
                .httpCode(HttpServletResponse.SC_BAD_REQUEST)
                .msg(exception.getMessage())
                .build();
        ErrorCodeEnum errorCodeEnum;
        if (exception instanceof AccountExpiredException) {
            errorCodeEnum = ErrorCodeEnum.ACCOUNT_EXPIRED;
            errorCode = errorCodeEnum.convert();
        }
        ResultUtil.sendFail(request, response, errorCode);
    }
}
